#===============================================================================
# Koro Business Environment
# Copyright (C) 2006,2008,2010,2011  Antonio Corroppoli
#
#This file is part of Koro BE.
# 
# Koro BE is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# Koro BE is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with Koro BE; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#===============================================================================

print 'importo korogui'
import sys
import wx
#import wx.aui
from koro import version, ksettings
from koro.util import to_bool
from koro.core import interface
#from koro.ui.wxgui.mellcfg import mShowFullScreen,FONT_SIZE
#from koro.ui.wxgui.widgets.controls import DefaultToolBar
from koro.ui.wxgui import images#,map
from koro.ui.wxgui.widgets import controls

mMSG_ERROR = wx.ICON_ERROR
mMSG_INFO  = wx.ICON_INFORMATION

#===============================================================================
# KoroSplashScreen
#===============================================================================
class KoroSplashScreen(wx.SplashScreen):
    def __init__(self):
        bmp = images.getSplashBitmap()
        wx.SplashScreen.__init__(self, bmp,
                                 wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT,#wx.SPLASH_NO_TIMEOUT,
                                 3000, None, -1)
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.fc = wx.FutureCall(2000, self.ShowMain)


    def OnClose(self, evt):
        # Make sure the default handler runs too so this window gets
        # destroyed
        evt.Skip()
        self.Hide()
        
        # if the timer is still running then go ahead and show the
        # main frame now
        if self.fc.IsRunning():
            self.fc.Stop()
            self.ShowMain()


    def ShowMain(self):
        #frame = MainFrame(None)
        #wx.GetApp().set_main_frame(frame)
        #frame.Show()
        if self.fc.IsRunning():
            self.Raise()
            

#===============================================================================
# KoroGui
#===============================================================================
class KoroGui(wx.App,interface.Observable):
    def __init__(self,observer,redirect=True,filename=None):
        wx.App.__init__(self,redirect,filename)
        interface.Observable.__init__(self)
        #interface.Observer.__init__(self)
        #self.__main.setEventHandler(handler)
        self.attach(observer)

#        self.__main._do_menu_bar()
#        self.__main.Enable(True)
#        self.__main.SetTransparent(255)
#        self.__main._set_home_page()        
    
    def OnInit(self):
        # Give a name to the wx.App
        name = "Koro Business Environment"
        self._checker = wx.SingleInstanceChecker(name)
        if self._checker.IsAnotherRunning():
            msgD = wx.MessageDialog(None,"Another program instance is already running, aborting.",style=wx.OK|wx.ICON_ERROR)
            msgD.ShowModal()
            msgD.Destroy()
            #raise Exception("Another program instance is already running, aborting.")
            return False
        
        #self.show_splash()
        wx.SetDefaultPyEncoding('utf-8')
        wx.InitAllImageHandlers()
        #self.__main=None
               
        #self.SetTopWindow(self.main)
        
        self.__main = MainFrame(None)
##        self.__main.Maximize(True)
        #self.__main.SetInitialSize((800,600))#780
        self.__main.SetInitialSize((780,510))
##        self.__main.SetClientSize((800,600))
##        self.__main.SetMinSize((800,700))
        #self.__main.CenterOnScreen()
        #mShowFullScreen and self.__main.ShowFullScreen(True, wx.CAPTION | wx.SYSTEM_MENU | wx.RESIZE_BORDER |wx.SUNKEN_BORDER | wx.NO_FULL_REPAINT_ON_RESIZE | wx.ICONIZE)
        self.SetTopWindow(self.__main)
#        self.__main.Maximize()
#        self.__main.Center()
        
        #self.Yield()        
        #self.__main.Show()
        #self.__main.Enable(False)
        #self.__main.SetTransparent(200)
        return True
    
    def show(self):
        self.__main.Maximize()
        self.__main.Center()
        self.__main.Show()
        self.__main.Enable(False)
        self.__main.SetTransparent(200)
        
        #self.__main._do_menu_bar()
        self.__main.Enable(True)
        self.__main.SetTransparent(255)
        self.__main._set_home_page()
        #self.close_splash()
        #self._splash.Hide()
    
    def clear_instance(self):
        print 'cancello checker'
        if sys.platform.startswith('win'):
            return
        del self._checker#su windows si cancella automaticamente

    def show_message(self,msg,style=wx.OK|wx.ICON_INFORMATION):
        msgD = wx.MessageDialog(self.__main,str(msg),style=style)
        response=msgD.ShowModal()
        msgD.Destroy()
        return response
    
    def show_error(self,msg):
        return self.show_message(msg, style=wx.OK|wx.ICON_ERROR)
    
    def show_question(self,msg):
        return self.show_message(msg,style=wx.YES_NO|wx.ICON_QUESTION)

    def show_splash(self):
        """
        Shows a splash window with the given image.  Input parameter 'image' can either be a wx.Bitmap or a filename.
        """        
        #self._splash = wx.SplashScreen(splash_bmp, wx.SPLASH_CENTRE_ON_SCREEN|wx.SPLASH_NO_TIMEOUT, 0, None, -1, style=wx.SIMPLE_BORDER|wx.FRAME_NO_TASKBAR)
        self._splash=KoroSplashScreen()
        self._splash.Show()

    def close_splash(self):
        """
        Closes the splash window.
        """
        if self._splash:
            self._splash.Close(True)

    def get_main_frame(self):
        return self.__main
    
    def main_frame(self):
        return self.__main

    def get_opzioni(self):
        return self.get_observer().get_options()
    
    def get_opzione(self,opt):
        return self.get_observer().get_option(opt)
    
    def set_main_frame(self,frame):
        self.__main=frame
        self.__main.SetInitialSize((780,510))        
        self.SetTopWindow(self.__main)
    

#===============================================================================
# KoroTaskBarIcon
#===============================================================================
class KoroTaskBarIcon(wx.TaskBarIcon):
    def __init__(self, frame):
        wx.TaskBarIcon.__init__(self)

        self.frame = frame
        self.SetIcon(wx.IconFromBitmap(images.getLogo24TaskBitmap()))
        self.Bind(wx.EVT_MENU, self.OnTaskBarActivate, id=1)
        self.Bind(wx.EVT_MENU, self.OnTaskBarDeactivate, id=2)
        self.Bind(wx.EVT_MENU, self.OnTaskBarClose, id=3)

    def CreatePopupMenu(self):
        menu = wx.Menu()
        menu.Append(1, 'Show')
        menu.Append(2, 'Hide')
        menu.Append(3, 'Close')
        return menu

    def OnTaskBarClose(self, event):
        self.frame.Close()

    def OnTaskBarActivate(self, event):
        if not self.frame.IsShown():
            self.frame.Show()
        self.frame.Raise()

    def OnTaskBarDeactivate(self, event):
        if self.frame.IsShown():
            self.frame.Hide()


[mID_MENUANACLI, mID_MENUANAZ, mID_MENUEXIT, mID_STATUSBAR,
 mID_MAINFRAME,mID_MENUABOUT,mID_MENUPROD,gID_CATEGPROD_PAGE,
 gID_ORDFORN_PAGE,gID_ORDCLI_PAGE,gID_TOOL_NEW,gID_TOOL_DELETE,gID_TOOL_SAVE,
 gID_ANACLI_PAGE,gID_ANAFORN_PAGE,gID_PROD_PAGE,gID_LISTINI_PAGE,gID_MAINFRAME_BOOK,
 gID_CODIVA_PAGE,gID_MOV_PAGE,ID_FATTURE_PAGE,ID_BANCO_PAGE,ID_AGENDA_PAGE,
 ID_OPZIONI_PAGE,ID_HOME_PAGE,ID_CALC,ID_INVENTARIO_PAGE,
 ID_ARRIVI_MERCE_PAGE,ID_REGISTRAZIONI_PAGE,ID_FCIVA_PAGE,ID_DDT_PAGE,
 ID_SITUAZIONEMAGAZ_PAGE,
] = [wx.NewId() for _mId in range(32)]
#===============================================================================
# MainFrame
#===============================================================================
class MainFrame(wx.Frame):
    MAX_PAGES=5
    def __init__(self, parent):
        wx.Frame.__init__(self, 
                          parent, 
                          title="{0} - v{1}  < {2} >".format(ksettings.APP_NAME,
                                                          version,
                                                          ksettings.DB_NAME))
        icon_boundle=wx.IconBundle()
        logo=wx.IconFromBitmap(images.getLogo16Bitmap())        
        icon_boundle.AddIcon(logo)
        logo=wx.IconFromBitmap(images.getLogo24Bitmap())
        icon_boundle.AddIcon(logo)
        logo=wx.IconFromBitmap(images.getLogo32Bitmap())
        icon_boundle.AddIcon(logo)
        logo=wx.IconFromBitmap(images.getLogo48Bitmap())
        icon_boundle.AddIcon(logo)
        self.SetIcons(icon_boundle)
#        self.SetIcon(wx.IconFromBitmap(images.getLogo4Bitmap()))
##                          style=wx.SUNKEN_BORDER|wx.MINIMIZE_BOX|wx.MAXIMIZE_BOX|wx.SYSTEM_MENU|wx.CAPTION|wx.CLOSE_BOX|wx.CLIP_CHILDREN)
        #self.SetFont(wx.Font(FONT_SIZE,wx.FONTFAMILY_DEFAULT,wx.FONTSTYLE_NORMAL,wx.FONTWEIGHT_NORMAL))        
        self.__pages=[]
        self._taskbar=KoroTaskBarIcon(self)
        #mainsizer=wx.BoxSizer()
        #self.__mainPanel = panels.getMainPanel(self)
        #mainsizer.Add(self.__mainPanel,1,wx.EXPAND)
        #self.SetSizer(mainsizer)
        # self._do_menu_bar()
        #toolbar
        self._mgr=None
        self.__do_layout()
        self.__bind()        
##        self._do_status_bar()
        #self.Bind(wx.EVT_LIST_ITEM_SELECTED,self.__setSelected)
        #self.Bind(hl.EVT_HYPERLINK_LEFT,self.OnDati)
        #self.SetAutoLayout(True)
        self.Layout()
        #self.Fit()
    
    def __do_layout(self):
        self._mgr = controls.KoroPageManager(self)
        self._main_panel=wx.Panel(self)
        self._main_panel.Hide()
        #self._mgr.set_managed_window(self)
        #self._mgr.Update()
        
    def __bind(self):        
#        self.GetToolBar().Bind(wx.EVT_TOOL, self.on_tool)#catch all tool events
        self.Bind(wx.EVT_MENU, self._on_menu)        
        #self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGING, self.on_page_changing,id=self.page_container.GetId())
        #self.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
        #self.Bind(fnb.EVT_NOTEBOOK_PAGE_CLOSING, self.on_page_closing,id=self.page_container.GetId())
        self.Bind(wx.EVT_CLOSE,self.on_close,id=self.GetId())
    
    def on_page_closing(self,evt):
        print 'main, page close'
        #self.__pages.remove(self.GetNotebook().GetPage(evt.GetSelection()).GetId())
        self.page_container.GetPage(evt.GetSelection()).before_close()   
    
    def on_page_changing(self,evt):
        print self.__class__.__name__,'on page changing'
        old=evt.GetOldSelection()
        if old>=0:
            page = self.page_container.GetPage(old)            
            page.on_kill_page_focus()        
        page = self.page_container.GetPage(evt.GetSelection())        
        if page:
            page.on_page_focus()
        evt.Skip()
    
    def _show_calculator(self,cmd):
        busycursor=wx.BusyCursor()
        import os,sys
        if cmd and 'linux' in sys.platform:
            cmd+=' &'        
        try:
            os.system(cmd)
        except Exception, err:
            wx.GetApp().show_error(err)
        finally:
            del busycursor

    def _set_home_page(self):
        pass
#        from koro.ui.wxgui import home
#        page=home.HomePage(parent=self)
#        if self.select_page(page):
#            return
#        self.page_container.AddPage(page, page.TITLE, True)        

    def do_menu_bar(self,configuration):
        #opzioni=wx.GetApp().get_opzioni()
        menubar = wx.MenuBar()
        self._do_main_menu(menubar)
        configuration.configure_view(menubar)
        #self._do_anag_menu(menubar)
        #self._do_product_menu(menubar)
        #self._do_doc_menu(menubar)
        #if to_bool(opzioni.GESTIONE_MAGAZZINO):
        #    self._do_magaz_menu(menubar)
        self._do_help_menu(menubar)
        self.SetMenuBar(menubar)        

    def _do_main_menu(self,menubar):
        opzioni=wx.GetApp().get_opzioni()
        main_menu = wx.Menu()
        main_menu.SetEvtHandlerEnabled(False)
        #main_menu.Append(help='Pagina Iniziale',id=ID_HOME_PAGE,text='Pagina Iniziale\tCtrl+I')
        #main_menu.AppendSeparator()
        #main_menu.Append(help='Agenda',id=ID_AGENDA_PAGE,text='Agenda\tCtrl+A')
        main_menu.Append(help='Preferenze',id=ID_OPZIONI_PAGE,text='Preferenze')
        if to_bool(opzioni.CALC):
            main_menu.AppendSeparator()
            main_menu.Append(help='Calcolatrice',id=ID_CALC,text='Calcolatrice\tCtrl+X')
        main_menu.AppendSeparator()        
        main_menu.Append(help='Esce da Koro',id=mID_MENUEXIT,text='Esci\tCtrl+Q')
        menubar.Append(menu=main_menu, title='Koro')
        self.Bind(wx.EVT_MENU, self.on_exit,id=mID_MENUEXIT)

    def _do_help_menu(self,menubar):
        main_menu = wx.Menu()
        main_menu.SetEvtHandlerEnabled(False)
        main_menu.AppendSeparator()
        main_menu.Append(help='About Koro',id=mID_MENUABOUT,text='About Koro BE')
        menubar.Append(menu=main_menu, title='Help')
        self.Bind(wx.EVT_MENU, self.on_about,id=mID_MENUABOUT)
        
    def _do_status_bar(self):
        statusBar = wx.StatusBar(id=mID_STATUSBAR,name='statusBar',parent=self,style=wx.CLIP_CHILDREN|wx.ALWAYS_SHOW_SB)
        statusBar.SetFieldsCount(1)
        statusBar.SetStatusText(number=0, text='stato')
        statusBar.SetStatusWidths([-1])
        self.SetStatusBar(statusBar)
    
#    def index_of(self,page):
#        num_pages=self.page_container.GetPageCount()
#        for i in range(num_pages):
#            p=self.page_container.GetPage(i)
#            if p.TITLE==page.TITLE:
#                return i
#        return -1
    
#    def select_page(self,page):
#        p=self.page_container.get_page()
#        if p.TITLE==page.TITLE:
#            return True
#        return False   
        
#    # Metodo usato da GuiFacade    
#    def add_page(self,page,objects,context,*args,**kwargs):
#        '''Metodo per aggiungere nuove pagine dati. Viene usato nella versione multipagine'''
#        #assert isinstance(page, panels.Page)
#        if self.select_page(page):
#            return
#        if self.page_container.GetPageCount()==MainFrame.MAX_PAGES:
#            wx.GetApp().show_message("Raggiunto il numero massimo di pagine aperte!")            
#            return
#        self.page_container.AddPage(page(self,context,objects,*args,**kwargs), page.TITLE, True)
    
    def show_page(self,page,objects,context,*args,**kwargs):
        '''Metodo per visualizzare la pagina dati. Viene usato nella versione a pagina singola'''
        if self._mgr.is_center_pane(page.TITLE):
            return
        self.Freeze()
        self._mgr.show_center_pane(page,
                                   self._main_panel,
                                   context,
                                   objects,*args,**kwargs)
        self.Thaw()
       
    def on_exit(self,evt):
        #TODO: verificare se viene fatto tutto prima di uscire
        #queto metodo viene chiamato da menu (voce Esci)
        print 'onexit'
        self.Close()
        evt.Skip(False)
    
    def on_close(self,evt):        
        wx.GetApp().clear_instance()
        self._mgr.un_init()
        wx.GetApp().get_observer().notify_closing()#deve stare dopo mgr.un_init()
        del self._mgr
        self._taskbar.Destroy()
        evt.Skip()

    def on_about(self,evt):
        import koro.ui.wxgui.widgets.dialogs
        koro.ui.wxgui.widgets.dialogs.show_about_dialog(self)
        del koro.ui.wxgui.widgets.dialogs
        evt.Skip(False)
    
    def _on_menu(self,event):
        '''Cattura tutti gli eventi generati dal menu. Recupera il contesto dalla mappa
        definita nel modulo map.py e richiede la visualizzazione della pagina.'''
        print 'MainFrame _on_menu'
        #opzioni=wx.GetApp().get_opzioni()
        EVT_ID=event.GetId()
        if EVT_ID==mID_MENUEXIT or EVT_ID==mID_MENUABOUT:
            event.Skip(False)
            return
        if EVT_ID==ID_CALC:
            opzioni=wx.GetApp().get_opzioni()
            self._show_calculator(opzioni.CALC_CMD)
            return
        self.Freeze()
        #context=map.context_by(event.GetId())
        observer=wx.GetApp().get_observer()
        #observer.set_context(context)
        observer.process_request(EVT_ID)        
        self.Thaw()
        event.Skip(False)    
        

if __name__ == '__main__':
    #main()
    application = KoroGui(interface.Observer(),0)
    application.MainLoop()
    print 'fine'
